package service

import (
	"app/common"
	"app/global"
	"app/model"
	mongodbutil "app/pkg/db"
	"fmt"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

type JobService struct {
}

func (u JobService) Save(info model.JobInfo) {
	collection, ctx := mongodbutil.GetCollection(global.App.Config.DBConf.DBName, common.JobInfoCollection)
	rr, err := collection.InsertOne(ctx, info)
	if err != nil {
		fmt.Println(err)
		fmt.Println(rr)
	}
	fmt.Println(rr.InsertedID)

}

func (u JobService) BatchSave(infos []model.JobInfo) {
	collection, ctx := mongodbutil.GetCollection(global.App.Config.DBConf.DBName, common.JobInfoCollection)
	docs := make([]interface{}, len(infos))
	for i, info := range infos {
		info.ID = uuid.NewString()
		docs[i] = info
	}
	rr, err := collection.InsertMany(ctx, docs, options.InsertMany())
	if err != nil {
		fmt.Println(err)
		fmt.Println(rr)
	}
	fmt.Println(rr)

}

func (u JobService) Update(info model.JobInfo) {
	collection, ctx := mongodbutil.GetCollection(global.App.Config.DBConf.DBName, common.JobInfoCollection)
	filter := bson.D{{"id", info.ID}}
	update := bson.D{
		{"$set", bson.D{
			{"fullname", info.FullName},
		}},
	}
	_, err := collection.UpdateOne(ctx, filter, update)
	if err != nil {
		log.Fatal(err)
	}
}

func (u JobService) Get(id string) model.JobInfo {
	collection, ctx := mongodbutil.GetCollection(global.App.Config.DBConf.DBName, common.JobInfoCollection)
	filter := bson.D{{"id", id}}
	cur, err := collection.Find(ctx, filter)
	if err != nil {
		log.Fatal(err)
	}
	var results []model.JobInfo
	if err = cur.All(ctx, &results); err != nil {
		log.Fatal(err)
	}

	for _, result := range results {
		fmt.Println(result)
	}
	if len(results) == 0 {
		return model.JobInfo{}
	}
	return results[0]

}
